﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Argotic.Common;
using System.Xml.XPath;
using Argotic.Data.Adapters;
using Argotic.Syndication;
using HtmlAgilityPack;
using System.Text.RegularExpressions;

namespace MyPublish.Connection.Syndication.AspNet
{
    [DataConnectionProvider(Name = "AspNet", Type = typeof(AspNetConnectionProvider))]
    public class AspNetConnectionProvider : DataConnectionProvider
    {
        public const string BLOG_URI = "http://weblogs.asp.net/";

        public override IEnumerable<object> ExecuteQuery()
        {
            List<object> items = new List<object>();

            string url = BLOG_URI + ConnectionString.UserName;
            HtmlDocument document = null;
            HtmlWeb web = null;
            try
            {
                web = new HtmlWeb();
                document = web.Load(url, "GET");
            }
            catch (Exception e)
            {
                throw new DataConnectionException("Failed to load ur  l " + url, e);
            }

            // srkirkland/archive/2010/04.aspx
            string pattern = string.Format(@"/{0}/archive/\d+/\d+\.aspx", ConnectionString.UserName);
            HtmlNodeCollection linkNodes = document.DocumentNode.SelectNodes("//a");
            foreach (HtmlNode linkNode in linkNodes)
            {
                string href = linkNode.GetAttributeValue("href", string.Empty);
                if (Regex.IsMatch(href, pattern))
                {
                    string feedUrl = BLOG_URI + href;
                    items.Add(new BlogData()
                    {
                        ID = ConnectionString.UserName,
                        BlogURL = url,
                        Title = ConnectionString.UserName,
                        UserName = ConnectionString.UserName,
                        FeedURL = feedUrl,
                        PostURL = string.Empty,
                        SelfFeedURL = feedUrl
                    });
                }
            }

            return items;
        }

        public override IEnumerable<object> ExecuteQuery(object data)
        {
            BlogData blogdata = data as BlogData;

            HtmlDocument document = null;
            HtmlWeb web = null;
            try
            {
                web = new HtmlWeb();
                document = web.Load(blogdata.Url, "GET");
            }
            catch (Exception e)
            {
                throw new DataConnectionException("Failed to load url " + blogdata.Url, e);
            }

            HtmlNodeCollection postNodes = document.DocumentNode.SelectNodes("//div[@class='post']");
            foreach (HtmlNode postNode in postNodes)
            {
                string link = string.Empty;
                string title = string.Empty;
                string content = string.Empty;
                DateTime publishedDate = DateTime.Now;
                try
                {
                    HtmlNode postHeadNode =  postNode.SelectSingleNode("div[@class='posthead']");
                    HtmlNode postContentNode = postNode.SelectSingleNode("div[@class='postcontent']");

                    HtmlNode titleLinkNode = postHeadNode.SelectSingleNode("h2/a");
                    link = titleLinkNode.GetAttributeValue("href", string.Empty);
                    title = titleLinkNode.InnerText;
                    content = postContentNode.InnerHtml;

                    try
                    {
                        string[] splits = link.Split(new char[]{'/'});
                        string dayString = splits[splits.Length-2].TrimStart(new char[]{'0'});
                        string monthString = splits[splits.Length-3].TrimStart(new char[]{'0'});
                        string yearString = splits[splits.Length-4].TrimStart(new char[]{'0'});

                        publishedDate = 
                            new DateTime(int.Parse(yearString),int.Parse(monthString),int.Parse(dayString));
                    }
                    catch{}
                }
                catch (Exception e) 
                { 
                    continue;
                }

                if (!string.IsNullOrEmpty(content))
                {
                    link = BLOG_URI.TrimEnd(new char[]{'/'}) + link;
                    PostData item  = new PostData()
                    {
                        Content = new PostContent()
                        {
                            AbsoluteUri = link,
                            Content = content,
                            Type = PostTextType.Html.ToString()
                        },
                        Link = new Uri(link),
                        Published = publishedDate,
                        Title = new PostText()
                        {
                            Text = title,
                            Type = PostTextType.Text
                        }
                    };

                    yield return item;
                }
            }
        }
    }
}
